package com.cc.monitor.db;

import com.cc.monitor.entity.job.protocol.JdbcProtocol;
import com.zaxxer.hikari.HikariDataSource;
import org.noear.solon.annotation.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * DynamicDb
 *
 * @author aa
 * @version 1.0
 * @since 2024/11/22
 */
@Component
public class DynamicDb {

    private final Map<String, HikariDataSource> dbMap = new HashMap<>(1);

    public void connDb(JdbcProtocol jdbc) {
        HikariDataSource db = new HikariDataSource();
        db.setPassword(jdbc.getPassword());
        db.setUsername(jdbc.getUsername());
        db.setJdbcUrl(jdbc.getUrl());
        db.setConnectionTimeout(30000);
        db.setMaximumPoolSize(100);
        db.setPoolName("mysql-monitor");
        db.setKeepaliveTime(60000);
        db.setConnectionTestQuery("SELECT 1;");
        dbMap.put("ds", db);
    }

    public DataSource getDb() {
        DataSource dataSource = dbMap.get("ds");
        if (dataSource == null) {
            for (HikariDataSource db : dbMap.values()) {
                db.close();
            }
            dbMap.clear();
            throw new RuntimeException("请连接数据库");
        }
        return dataSource;
    }

    public Connection getConnection() throws SQLException {
        return getDb().getConnection();
    }
}
